package com.cg.service.impl;

import com.cg.dto.InterviewSessionDTO;
import com.cg.dto.InterviewMessageDTO;
import com.cg.dto.InterviewEvaluationDTO;
import com.cg.mapper.InterviewSessionMapper;
import com.cg.service.InterviewSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 面试会话管理服务实现类
 */
@Slf4j
@Service
public class InterviewSessionServiceImpl implements InterviewSessionService {
    
    @Autowired
    private InterviewSessionMapper interviewSessionMapper;
    
    @Override
    public InterviewSessionDTO createSession(Long userId, Long interviewId, String sessionTitle, 
                                           String interviewerType, String topics, 
                                           Integer classicCount, Integer projectCount) {
        try {
            InterviewSessionDTO session = new InterviewSessionDTO();
            session.setUserId(userId);
            
            // 如果interviewId为null，使用一个临时值，避免数据库约束错误
            // 后续会更新为正确的sessionId
            if (interviewId == null) {
                session.setInterviewId(0L); // 使用临时值，避免null约束
            } else {
                session.setInterviewId(interviewId);
            }
            
            session.setSessionTitle(sessionTitle);
            session.setInterviewerType(interviewerType);
            session.setTopics(topics);
            session.setClassicCount(classicCount);
            session.setProjectCount(projectCount);
            session.setStatus("active");
            session.setCreateTime(new Date());
            session.setUpdateTime(new Date());
            
            int result = interviewSessionMapper.createSession(session);
            if (result <= 0) {
                throw new RuntimeException("创建面试会话失败");
            }
            
            // 如果interviewId为null，更新为sessionId
            if (interviewId == null) {
                session.setInterviewId(session.getId());
                // 更新数据库中的interview_id字段
                interviewSessionMapper.updateInterviewId(session.getId(), session.getId());
            }
            
            log.info("面试会话创建成功: sessionId={}, userId={}, interviewId={}", 
                    session.getId(), userId, session.getInterviewId());
            
            return session;
            
        } catch (Exception e) {
            log.error("创建面试会话失败: userId={}, interviewId={}, error={}", 
                    userId, interviewId, e.getMessage(), e);
            throw new RuntimeException("创建面试会话失败", e);
        }
    }
    
    @Override
    public InterviewSessionDTO getSessionById(Long id) {
        try {
            return interviewSessionMapper.getSessionById(id);
        } catch (Exception e) {
            log.error("获取面试会话失败: id={}, error={}", id, e.getMessage(), e);
            throw new RuntimeException("获取面试会话失败", e);
        }
    }
    
    @Override
    public List<InterviewSessionDTO> getUserSessions(Long userId) {
        try {
            return interviewSessionMapper.getSessionsByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户面试会话列表失败: userId={}, error={}", userId, e.getMessage(), e);
            throw new RuntimeException("获取用户面试会话列表失败", e);
        }
    }
    
    @Override
    public InterviewSessionDTO getSessionByInterviewId(Long interviewId) {
        try {
            return interviewSessionMapper.getSessionByInterviewId(interviewId);
            } catch (Exception e) {
            log.error("根据面试ID获取会话失败: interviewId={}, error={}", interviewId, e.getMessage(), e);
            throw new RuntimeException("根据面试ID获取会话失败", e);
        }
    }
    
    @Override
    public void updateSessionStatus(Long id, String status) {
        try {
            int result = interviewSessionMapper.updateSessionStatus(id, status);
            if (result <= 0) {
                throw new RuntimeException("更新面试会话状态失败");
            }
            log.info("面试会话状态更新成功: id={}, status={}", id, status);
        } catch (Exception e) {
            log.error("更新面试会话状态失败: id={}, status={}, error={}", id, status, e.getMessage(), e);
            throw new RuntimeException("更新面试会话状态失败", e);
        }
    }
    
    @Override
    public void deleteSession(Long id, Long userId) {
        try {
            int result = interviewSessionMapper.deleteSession(id, userId);
            if (result <= 0) {
                throw new RuntimeException("删除面试会话失败");
            }
            log.info("面试会话删除成功: id={}, userId={}", id, userId);
        } catch (Exception e) {
            log.error("删除面试会话失败: id={}, userId={}, error={}", id, userId, e.getMessage(), e);
            throw new RuntimeException("删除面试会话失败", e);
        }
    }
    
    @Override
    public void addUserMessage(Long sessionId, String content) {
        try {
            if (!StringUtils.hasText(content)) {
                return;
            }
            
            int messageOrder = interviewSessionMapper.getMessageCountBySessionId(sessionId) + 1;
            
            InterviewMessageDTO message = new InterviewMessageDTO();
            message.setSessionId(sessionId);
            message.setRole("user");
            message.setContent(content);
            message.setMessageOrder(messageOrder);
            message.setCreateTime(new Date());
            
            int result = interviewSessionMapper.addMessage(message);
            if (result <= 0) {
                throw new RuntimeException("添加用户消息失败");
            }
            
            log.info("用户消息添加成功: sessionId={}, messageOrder={}", sessionId, messageOrder);
            
        } catch (Exception e) {
            log.error("添加用户消息失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            throw new RuntimeException("添加用户消息失败", e);
        }
    }
    
    @Override
    public void addAssistantMessage(Long sessionId, String content) {
        try {
            if (!StringUtils.hasText(content)) {
                return;
            }
            
            int messageOrder = interviewSessionMapper.getMessageCountBySessionId(sessionId) + 1;
            
            InterviewMessageDTO message = new InterviewMessageDTO();
            message.setSessionId(sessionId);
            message.setRole("assistant");
            message.setContent(content);
            message.setMessageOrder(messageOrder);
            message.setCreateTime(new Date());
            
            int result = interviewSessionMapper.addMessage(message);
            if (result <= 0) {
                throw new RuntimeException("添加面试官消息失败");
            }
            
            log.info("面试官消息添加成功: sessionId={}, messageOrder={}", sessionId, messageOrder);
            
        } catch (Exception e) {
            log.error("添加面试官消息失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            throw new RuntimeException("添加面试官消息失败", e);
        }
    }
    
    @Override
    public List<InterviewMessageDTO> getSessionMessages(Long sessionId) {
        try {
            return interviewSessionMapper.getMessagesBySessionId(sessionId);
        } catch (Exception e) {
            log.error("获取会话消息失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            throw new RuntimeException("获取会话消息失败", e);
        }
    }
    
    @Override
    public void saveEvaluation(Long sessionId, String overallScore, String strengths, 
                             String weaknesses, String suggestions) {
        try {
            InterviewEvaluationDTO evaluation = new InterviewEvaluationDTO();
            evaluation.setSessionId(sessionId);
            evaluation.setOverallScore(overallScore);
            evaluation.setStrengths(strengths);
            evaluation.setWeaknesses(weaknesses);
            evaluation.setSuggestions(suggestions);
            evaluation.setCreateTime(new Date());
            
            int result = interviewSessionMapper.saveEvaluation(evaluation);
            if (result <= 0) {
                throw new RuntimeException("保存面试评估结果失败");
            }
            
            log.info("面试评估结果保存成功: sessionId={}, score={}", sessionId, overallScore);
            
        } catch (Exception e) {
            log.error("保存面试评估结果失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            throw new RuntimeException("保存面试评估结果失败", e);
        }
    }
    
    @Override
    public InterviewEvaluationDTO getEvaluationBySessionId(Long sessionId) {
        try {
            return interviewSessionMapper.getEvaluationBySessionId(sessionId);
        } catch (Exception e) {
            log.error("获取面试评估结果失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            throw new RuntimeException("获取面试评估结果失败", e);
        }
    }
}
